from sqlalchemy import Column, String, DateTime, ForeignKey, Text, Integer, Boolean, Enum
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.database.base import Base
from app.models.maintenance_record import MaintenanceType
import uuid
import enum

class PlanFrequency(str, enum.Enum):
    """计划频率枚举"""
    DAILY = "daily"  # 每日
    WEEKLY = "weekly"  # 每周
    MONTHLY = "monthly"  # 每月
    QUARTERLY = "quarterly"  # 每季度
    SEMI_ANNUALLY = "semi_annually"  # 每半年
    ANNUALLY = "annually"  # 每年
    CUSTOM = "custom"  # 自定义

class MaintenancePlan(Base):
    """设备维护计划模型"""
    __tablename__ = "maintenance_plans"
    
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    device_id = Column(UUID(as_uuid=True), ForeignKey("devices.id"), nullable=False, index=True)
    maintenance_type = Column(Enum(MaintenanceType), nullable=False, index=True)
    
    # 基本信息
    title = Column(String(255), nullable=False)
    description = Column(Text)
    priority = Column(String(20), default="medium")
    
    # 计划设置
    frequency = Column(Enum(PlanFrequency), nullable=False)
    interval_days = Column(Integer)  # 自定义间隔天数(当频率为custom时使用)
    estimated_duration = Column(Integer)  # 预计持续时间(分钟)
    
    # 时间设置
    start_date = Column(DateTime(timezone=True), nullable=False)
    end_date = Column(DateTime(timezone=True))  # 空表示无限期
    last_execution = Column(DateTime(timezone=True))  # 最后执行时间
    next_execution = Column(DateTime(timezone=True), index=True)  # 下次执行时间
    
    # 人员设置
    default_assignee = Column(UUID(as_uuid=True), ForeignKey("users.id"))  # 默认分配给谁
    
    # 状态和配置
    is_active = Column(Boolean, default=True, index=True)  # 是否激活
    auto_create_records = Column(Boolean, default=True)  # 是否自动创建维护记录
    advance_notice_days = Column(Integer, default=3)  # 提前通知天数
    
    # 模板内容
    template_description = Column(Text)  # 模板描述
    template_checklist = Column(Text)  # 模板检查清单(JSON格式)
    
    # 系统字段
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    created_by = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
    
    # 关系
    device = relationship("Device", back_populates="maintenance_plans")
    default_assignee_user = relationship("User", foreign_keys=[default_assignee], back_populates="assigned_plans")
    creator = relationship("User", foreign_keys=[created_by], back_populates="created_plans")